package Optional;

import Lambda.dao.Employee;
import org.junit.Test;

import java.util.Optional;

/**
 * Optional.of(T t) : 创建一个 Optional 实例
 * Optional.empty() : 创建一个空的 Optional 实例
 * Optional.ofNullable(T t):若 t 不为 null,创建 Optional 实例,否则创建空实例
 * isPresent() : 判断是否包含值
 * orElse(T t) : 如果调用对象包含值，返回该值，否则返回t
 * orElseGet(Supplier s) :如果调用对象包含值，返回该值，否则返回 s 获取的值
 * map(Function f): 如果有值对其处理，并返回处理后的Optional，否则返回 Optional.empty()
 * flatMap(Function mapper):与 map 类似，要求返回值必须是Optional
 */
public class TestOptional {
    @Test
    public void testof() {
        Optional<Employee> optionalEmployee = Optional.of(new Employee());
        Employee employee = optionalEmployee.get();
        System.out.println(employee);
    }

    @Test
    public void testofNullable() {
        Optional<Employee> empty = Optional.ofNullable(null);

        System.out.println(empty.get());
    }

    @Test
    public void testempty() {
        Optional<Employee> empty = Optional.empty();

        System.out.println(empty.get());
    }

    @Test
    public void testisPresent() {
        Optional<Employee> empty = Optional.ofNullable(null);
        if (empty.isPresent()) {
            System.out.println(empty.get());
        }

    }

    @Test
    public void testorElse() {
        Optional<Employee> empty = Optional.ofNullable(new Employee());
        if (empty.isPresent()) {
            System.out.println(empty.get());
        }
        Employee employee = empty.orElse(new Employee("张三", 18, 888.88, Employee.Status.BUSY));
        System.out.println(employee);
    }

    @Test
    public void testorElseGet() {
        Optional<Employee> empty = Optional.ofNullable(new Employee());
        //if (empty.isPresent()){ System.out.println(empty.get());}
        Employee employee = empty.orElse(new Employee("张三", 18, 888.88, Employee.Status.BUSY));
        Employee employee1 = empty.orElseGet(() -> new Employee());
        System.out.println(employee1);
    }

    @Test
    public void testmap() {
        Optional<Employee> empty = Optional.ofNullable(new Employee("张三", 18, 888.88, Employee.Status.BUSY));
        //if (empty.isPresent()){ System.out.println(empty.get());}
        Optional<String> str = empty.map((e) -> e.getName());
        System.out.println(str.get());
    }

    @Test
    public void testflatMap() {
        Optional<Object> empty = Optional.ofNullable(new Employee("张三", 18, 888.88, Employee.Status.BUSY));
        //if (empty.isPresent()){ System.out.println(empty.get());}
        Optional<String> s = empty.flatMap(e -> Optional.of(e.getClass().getName()));
        System.out.println(s.get());
    }
}
